package com.gamebase.net.rpc
{
	import flash.utils.ByteArray;
	
	public class Guid 
	{
		private var b1:uint;
		private var b2:uint;
		private var b3:uint;
		private var b4:uint;
		
		static private var pattern:RegExp = new RegExp("\{[A-F0-9]{8}(-[A-F0-9]{4}){3}-[A-F0-9]{12}\}","i");
		static private var patValue:RegExp = new RegExp("[A-F0-9]+","ig");

		private function validate(str:String):Boolean
		{
			return pattern.test(str);
		}
		
		public function Guid(str:String=null)
		{
			if(str==null)
			{
				b1 = 0;
				b2 = 0;
				b3 = 0;
				b4 = 0;
			}
			else
			{
				this.parse(str);
			}
		}
		
		public function parse(str:String):Boolean
		{
			if(validate(str)==false) return false;
			
			var bytes:Array = str.match(patValue);
			
			var value:String = "";
			var index:int;
			for(index=0;index<bytes.length;index++)
			{
				value += bytes[index];
			}

			b1 = Number("0x"+value.slice(0,8));
			b2 = Number("0x"+value.slice(8,16));
			b3 = Number("0x"+value.slice(16,24));
			b4 = Number("0x"+value.slice(24,32));

			return true;
		}
		
	 	public function toString():String
		{
			var str:String = "{";
			str += fillZero(b1.toString(16),8);
			str += "-"
			str += fillZero(b2.toString(16),8).substr(0,4);
			str += "-";
			str += fillZero(b2.toString(16),8).substr(4,4);
			str += "-";
			str += fillZero(b3.toString(16),8).substr(0,4);
			str += "-";
			str += fillZero(b3.toString(16),8).substr(4,4);
			str += fillZero(b4.toString(16),8);
			str += "}";
			
			return str.toUpperCase();
		}
		
		public function getBytes(ba:ByteArray,length:uint):ByteArray
		{
			ba.writeUnsignedInt(b1);
			ba.writeUnsignedInt(b2);
			ba.writeUnsignedInt(b3);
			ba.writeUnsignedInt(b4);
			
			return ba;
		}
		
		public function setBytes(ba:ByteArray,length:uint):void
		{
			if(length>0)
			{
				b1 = ba.readUnsignedInt();
			}
			
			if(length>4)
			{
				b2 = ba.readUnsignedInt();
			}
			
			if(length>8)
			{
				b3 = ba.readUnsignedInt();
			}
			
			if(length>12)
			{
				b4 = ba.readUnsignedInt();
			}
		}
		
		static private function fillZero(str:String,length:int):String
		{
			while(length>str.length)
			{
				str = "0" + str;
			}		
			
			return str;
		}
		
	}
}